// app.js
App({
  onLaunch() {
    console.log('停车场预约小程序启动')
    
    // 检查本年度和季度
    this.checkYearAndQuarterReset()
    
    // 开发环境提示，直接显示调试信息
    console.log('辉瑞停车场预约小程序调试信息：')
    console.log('- 139开头的手机号可以登录系统')
    console.log('- 车牌号不做严格验证')
    console.log('- 预约额度分为当季度和下季度两部分')
    console.log('- 当季度额度在季度末清零')
    console.log('- 下季度额度从当季度最后一个月的最后一个周四开始可用')
    console.log('- 周一/周五消耗0.5次额度，周二至周四消耗1次额度')
  },
  
  globalData: {
    userInfo: null,
    systemConfig: {
      totalParkingSpots: 80,
      quarterlyQuota: 20
    }
  },
  
  // 获取季度的开始和结束日期
  getQuarterDates(year, quarter) {
    const startMonth = (quarter - 1) * 3
    const endMonth = startMonth + 2
    
    const startDate = new Date(year, startMonth, 1)
    const endDate = new Date(year, endMonth + 1, 0) // 当月最后一天
    
    return { startDate, endDate }
  },
  
  // 获取某个月的最后一个周四
  getLastThursdayOfMonth(year, month) {
    // 获取下个月第一天
    const firstDayOfNextMonth = new Date(year, month, 1)
    // 回到当月最后一天
    const lastDay = new Date(firstDayOfNextMonth)
    lastDay.setDate(lastDay.getDate() - 1)
    
    // 从当月最后一天开始向前查找第一个周四(4)
    const date = new Date(lastDay)
    
    while (date.getDay() !== 4) {
      date.setDate(date.getDate() - 1)
    }
    
    return date
  },
  
  // 检查年度和季度重置额度
  checkYearAndQuarterReset() {
    const now = new Date()
    const currentYear = now.getFullYear()
    const currentMonth = now.getMonth() + 1
    const currentQuarter = Math.ceil(currentMonth / 3)
    
    // 获取当前季度的结束月份
    const currentQuarterEndMonth = currentQuarter * 3 - 1
    
    // 获取用户信息
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) return
    
    console.log('检查用户额度重置:', userInfo.phone)
    
    // 初始化额度字段，如果不存在
    if (userInfo.current_quarter_quota_remaining === undefined) {
      userInfo.current_quarter_quota_remaining = this.globalData.systemConfig.quarterlyQuota
    }
    
    if (userInfo.next_quarter_quota_remaining === undefined) {
      userInfo.next_quarter_quota_remaining = 0
    }
    
    // 记录历史状态供调试
    const oldCurrentQuota = userInfo.current_quarter_quota_remaining
    const oldNextQuota = userInfo.next_quarter_quota_remaining
    
    // 检查用户信息中是否保存了年份和季度
    if (!userInfo.year) {
      userInfo.year = currentYear
    }
    
    if (!userInfo.quarter) {
      userInfo.quarter = currentQuarter
    }
    
    // 如果是新的一年或新的季度
    if (userInfo.year < currentYear || (userInfo.year === currentYear && userInfo.quarter < currentQuarter)) {
      // 记录原来的季度和年份
      const oldYear = userInfo.year
      const oldQuarter = userInfo.quarter
      
      // 更新为当前季度和年份
      userInfo.year = currentYear
      userInfo.quarter = currentQuarter
      
      // 如果是新的季度，当前季度额度重置为20，下季度额度重置为0
      userInfo.current_quarter_quota_remaining = this.globalData.systemConfig.quarterlyQuota
      userInfo.next_quarter_quota_remaining = 0
      
      console.log(`季度重置: ${oldYear}-Q${oldQuarter} -> ${currentYear}-Q${currentQuarter}`)
      
      // 如果是新年度，清理往年预约记录
      if (oldYear < currentYear) {
        this.clearLastYearReservations()
      }
    }
    
    // 检查是否需要发放下季度额度
    // 获取当前季度最后一个月的最后一个周四
    const lastMonthOfQuarter = currentQuarter * 3
    const lastThursday = this.getLastThursdayOfMonth(currentYear, lastMonthOfQuarter - 1) // 月份从0开始
    
    // 如果当前日期已经过了最后一个周四且下季度额度为0，则发放下季度额度
    if (now >= lastThursday && userInfo.next_quarter_quota_remaining === 0) {
      userInfo.next_quarter_quota_remaining = this.globalData.systemConfig.quarterlyQuota
      console.log(`下季度额度发放: +${this.globalData.systemConfig.quarterlyQuota}`)
    }
    
    // 如果额度有变动，保存并提示
    if (oldCurrentQuota !== userInfo.current_quarter_quota_remaining || oldNextQuota !== userInfo.next_quarter_quota_remaining) {
      console.log('额度更新:', {
        当季度: `${oldCurrentQuota} -> ${userInfo.current_quarter_quota_remaining}`,
        下季度: `${oldNextQuota} -> ${userInfo.next_quarter_quota_remaining}`
      })
      
      wx.setStorageSync('userInfo', userInfo)
      
      // 如果在前台，显示提示
      if (this.globalData.userInfo) {
        wx.showToast({
          title: `额度已更新: 当季度${userInfo.current_quarter_quota_remaining}次，下季度${userInfo.next_quarter_quota_remaining}次`,
          icon: 'none',
          duration: 3000
        })
      }
    }
  },
  
  // 清除往年的预约记录
  clearLastYearReservations() {
    const now = new Date()
    const currentYear = now.getFullYear()
    
    // 获取预约记录
    let reservations = wx.getStorageSync('reservations') || []
    console.log('清理预约记录, 当前总数:', reservations.length)
    
    // 只保留当年的预约
    const oldCount = reservations.length
    reservations = reservations.filter(item => {
      const reservationDate = new Date(item.date)
      return reservationDate.getFullYear() >= currentYear
    })
    
    console.log('清理完成, 清理数量:', oldCount - reservations.length)
    
    // 保存更新后的预约记录
    wx.setStorageSync('reservations', reservations)
  }
}) 